package com.budgetme.ui.fragments;

import com.budgetme.database.Database;

import android.app.Fragment;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public abstract class DetailsFragment extends Fragment {
	private static final String TAG = "DetailsFragment";
	
	public static final String ARG_ID = "ARG_ID";
	
	protected int mId;
	protected ContentResolver mContentResolver;
	
	private TextView[] to;
	private String[] from;
	private Uri uri;
	
	protected Cursor mDataCursor;
	protected Boolean mHasData;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		Bundle args = getArguments();
        if (args != null) {
            mId = args.getInt(ARG_ID);
        }
        
        setHasOptionsMenu(true);
        
        mContentResolver = getActivity().getContentResolver();
		
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    	Log.d(TAG, "onActivityCreated");
        
        to = getTo();
        from = getFrom();
        uri = getUri();
        
        if (to.length != from.length) {
        	Log.e(TAG, "To and From arrays are not the same length");
        	// TODO: Throw something here, for now it's fine
        }
        
        mDataCursor = mContentResolver.query(uri, null, null, null, null);
        
        mHasData = mDataCursor.moveToFirst();
        
        View fragment = getView();
        for (int i = 0; i < to.length; i++) {
        	
        	TextView v = to[i];
        	
        	int index = mDataCursor.getColumnIndex(from[i]);
        	
        	switch (mDataCursor.getType(index)) {
        		case Cursor.FIELD_TYPE_NULL :
        			break;
        			
        		case Cursor.FIELD_TYPE_INTEGER:
        			v.setText(String.valueOf(mDataCursor.getInt(index)));
        			break;
        			
        		case Cursor.FIELD_TYPE_FLOAT:
        			v.setText(String.format("%.0f", mDataCursor.getDouble(index)));
        			break;
        			
        		case Cursor.FIELD_TYPE_STRING:
        			v.setText(mDataCursor.getString(index));
        			break;
        			
				case Cursor.FIELD_TYPE_BLOB:
					break;
					
        	}
        	
        }
        
	}
	
	protected abstract TextView[] getTo();
	protected abstract String[] getFrom();
	protected abstract Uri getUri();

}
